<template>
  <el-card style="width: 100%;">
    <h2>入住登记管理</h2>
    <el-button type="primary" @click="openAdd">新增入住</el-button>
    <el-table :data="checkIns" style="width: 100%;margin-top:16px">
      <el-table-column prop="checkInId" label="ID" width="60" />
      <el-table-column label="客户姓名" width="100">
        <template #default="scope">
          {{ getCustomerName(scope.row.customerId) }}
        </template>
      </el-table-column>
      <el-table-column label="房间号" width="100">
        <template #default="scope">
          {{ getRoomNumber(scope.row.roomId) }}
        </template>
      </el-table-column>
      <el-table-column label="入住时间">
        <template #default="scope">
          {{ formatDate(scope.row.checkInDate) }}
        </template>
      </el-table-column>
      <el-table-column label="预计退房">
        <template #default="scope">
          {{ formatDate(scope.row.expectedCheckOutDate) }}
        </template>
      </el-table-column>
      <el-table-column prop="status" label="状态" width="100">
        <template #default="scope">
          <el-tag :type="getStatusType(scope.row.status)">
            {{ getStatusText(scope.row.status) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="initialDeposit" label="押金" width="100" />
      <el-table-column label="操作" width="180">
        <template #default="scope">
          <el-button size="small" @click="openEdit(scope.row)">编辑</el-button>
          <el-button size="small" type="danger" @click="onDelete(scope.row.checkInId)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-dialog v-model="dialogVisible" :title="dialogTitle" width="700px">
      <el-form :model="form" :rules="rules" ref="formRef" label-width="100px">
        <el-form-item label="客户" prop="customerId">
          <el-select v-model="form.customerId" placeholder="请选择客户" style="width: 100%">
            <el-option 
              v-for="customer in customers" 
              :key="customer.customerId" 
              :label="customer.fullName" 
              :value="customer.customerId" 
            />
          </el-select>
        </el-form-item>
        <el-form-item label="房间" prop="roomId">
          <el-select v-model="form.roomId" placeholder="请选择房间" style="width: 100%">
            <el-option 
              v-for="room in availableRooms" 
              :key="room.roomId" 
              :label="`${room.roomNumber} - ${getRoomTypeName(room.typeId)}`" 
              :value="room.roomId" 
            />
          </el-select>
        </el-form-item>
        <el-form-item label="入住时间" prop="checkInDate">
          <el-date-picker 
            v-model="form.checkInDate" 
            type="datetime" 
            placeholder="选择入住时间"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="预计退房" prop="expectedCheckOutDate">
          <el-date-picker 
            v-model="form.expectedCheckOutDate" 
            type="datetime" 
            placeholder="选择预计退房时间"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="押金" prop="initialDeposit">
          <el-input v-model="form.initialDeposit" type="number" placeholder="请输入押金金额" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="form.status" placeholder="请选择状态">
            <el-option label="活跃" value="active" />
            <el-option label="已退房" value="checked_out" />
            <el-option label="已取消" value="cancelled" />
          </el-select>
        </el-form-item>
        <el-form-item label="备注" prop="notes">
          <el-input v-model="form.notes" type="textarea" placeholder="请输入备注" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="onSubmit">确定</el-button>
      </template>
    </el-dialog>
  </el-card>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue';
import { getCheckIns, addCheckIn, updateCheckIn, deleteCheckIn } from '../api/checkIn';
import { getCustomers } from '../api/customer';
import { getRooms } from '../api/room';
import { getRoomTypes } from '../api/roomType';
import { useUserStore } from '../store/user';
import { ElMessage, ElMessageBox } from 'element-plus';

const userStore = useUserStore();
const checkIns = ref([]);
const customers = ref([]);
const rooms = ref([]);
const roomTypes = ref([]);
const dialogVisible = ref(false);
const dialogTitle = ref('');
const form = ref({ 
  checkInId: null, 
  customerId: '', 
  roomId: '', 
  userId: userStore.userInfo.userId || 1, // 使用当前登录用户的ID
  checkInDate: '', 
  expectedCheckOutDate: '', 
  actualCheckOutDate: null, 
  initialDeposit: '', 
  status: 'active', 
  notes: '' 
});
const formRef = ref();

const rules = {
  customerId: [{ required: true, message: '请选择客户', trigger: 'change' }],
  roomId: [{ required: true, message: '请选择房间', trigger: 'change' }],
  checkInDate: [{ required: true, message: '请选择入住时间', trigger: 'change' }],
  expectedCheckOutDate: [{ required: true, message: '请选择预计退房时间', trigger: 'change' }],
  initialDeposit: [{ required: true, message: '请输入押金', trigger: 'blur' }]
};

const loadCheckIns = async () => {
  checkIns.value = await getCheckIns();
};

const loadCustomers = async () => {
  customers.value = await getCustomers();
};

const loadRooms = async () => {
  rooms.value = await getRooms();
};

const loadRoomTypes = async () => {
  roomTypes.value = await getRoomTypes();
};

const getCustomerName = (customerId) => {
  const customer = customers.value.find(c => c.customerId === customerId);
  return customer ? customer.fullName : `客户${customerId}`;
};

const getRoomNumber = (roomId) => {
  const room = rooms.value.find(r => r.roomId === roomId);
  return room ? room.roomNumber : `房间${roomId}`;
};

const getRoomTypeName = (typeId) => {
  const roomType = roomTypes.value.find(type => type.typeId === typeId);
  return roomType ? roomType.typeName : `类型${typeId}`;
};

const getStatusType = (status) => {
  const types = {
    'active': 'success',
    'checked_out': 'info',
    'cancelled': 'danger'
  };
  return types[status] || 'info';
};

const getStatusText = (status) => {
  const texts = {
    'active': '活跃',
    'checked_out': '已退房',
    'cancelled': '已取消'
  };
  return texts[status] || status;
};

const formatDate = (dateStr) => {
  if (!dateStr) return '';
  return new Date(dateStr).toLocaleString();
};

const availableRooms = computed(() => {
  return rooms.value.filter(room => room.status === 'available');
});

const openAdd = () => {
  dialogTitle.value = '新增入住';
  form.value = { 
    checkInId: null, 
    customerId: '', 
    roomId: '', 
    userId: userStore.userInfo.userId || 1, 
    checkInDate: '', 
    expectedCheckOutDate: '', 
    actualCheckOutDate: null, 
    initialDeposit: '', 
    status: 'active', 
    notes: '' 
  };
  dialogVisible.value = true;
};

const openEdit = (row) => {
  dialogTitle.value = '编辑入住';
  form.value = { ...row };
  dialogVisible.value = true;
};

const onSubmit = () => {
  formRef.value.validate(async (valid) => {
    if (!valid) return;
    
    try {
      // 调试信息
      console.log('当前用户信息:', userStore.userInfo);
      console.log('当前用户ID:', userStore.userInfo.userId);
      
      // 准备提交的数据
      const submitData = {
        ...form.value,
        userId: userStore.userInfo.userId || 1, // 确保使用当前登录用户的ID
        checkInDate: form.value.checkInDate ? new Date(form.value.checkInDate).toISOString() : null,
        expectedCheckOutDate: form.value.expectedCheckOutDate ? new Date(form.value.expectedCheckOutDate).toISOString() : null,
        actualCheckOutDate: form.value.actualCheckOutDate ? new Date(form.value.actualCheckOutDate).toISOString() : null,
        initialDeposit: parseFloat(form.value.initialDeposit) || 0
      };
      
      console.log('提交的数据:', submitData);
      
      if (!form.value.checkInId) {
        console.log('提交新增数据:', submitData);
        const result = await addCheckIn(submitData);
        console.log('新增结果:', result);
        if (result) {
          ElMessage.success('新增成功');
          dialogVisible.value = false;
          loadCheckIns();
        } else {
          ElMessage.error('新增失败');
        }
      } else {
        console.log('提交修改数据:', submitData);
        const result = await updateCheckIn(submitData);
        console.log('修改结果:', result);
        if (result) {
          ElMessage.success('修改成功');
          dialogVisible.value = false;
          loadCheckIns();
        } else {
          ElMessage.error('修改失败');
        }
      }
    } catch (error) {
      console.error('操作失败:', error);
      ElMessage.error('操作失败: ' + error.message);
    }
  });
};

const onDelete = (id) => {
  ElMessageBox.confirm('确定要删除该入住记录吗？', '提示', { type: 'warning' })
    .then(async () => {
      await deleteCheckIn(id);
      ElMessage.success('删除成功');
      loadCheckIns();
    });
};

onMounted(() => {
  loadCheckIns();
  loadCustomers();
  loadRooms();
  loadRoomTypes();
});
</script> 